import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Dropdown, Menu, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { TableListItem, TreeNode } from './data.d';
import * as allIcons from '@ant-design/icons/es';
import { queryModule, updateModule, addModule, removeModule, queryTree } from './service';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addModule(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateModule(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeModule({
      key: selectedRows.map((row) => row.moduleId),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [treeData, setTreeData] = useState<TreeNode[]>();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      dataIndex: 'moduleName',
    },
    {
      title: '编码',
      dataIndex: 'moduleCode',
    },
    {
      title: '路径',
      dataIndex: 'relativePath',
      width: 200,
    },
    {
      title: '图标',
      dataIndex: 'iconClass',
      hideInSearch: true,
      renderText: (icon: string) => {
        const NewIcon = allIcons[icon] || allIcons[''.concat(icon, 'Outlined')];
        if (NewIcon) {
          return React.createElement(NewIcon);
        }
        return icon;
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'disable',
      hideInSearch: true,
      valueEnum: {
        0: { text: '启用', status: 'Success' },
        1: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  useEffect(() => {
    const queryTreeData = async () => {
      setTreeData(await queryTree({ type: 'root' }));
    };
    queryTreeData();
  }, []);

  return (
    <>
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="moduleId"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        tableAlertRender={(false)}
        request={(params) => queryModule(params)}
        columns={columns}
        rowSelection={{}}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={treeData}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          treeData={treeData}
        />
      ) : null}
    </>
  );
};

export default TableList;
